package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.UserRelation;
import org.aeon.entity.dto.UserDto;
import org.aeon.message.request.ListQueryRequestMessage;
import org.aeon.message.response.ListQueryResponseMessage;
import org.aeon.service.UserRelationService;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserRelationServiceFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * @author: MissingAeon
 * @date: 2024/1/30 10:05
 * @description: 好友成员请求消息
 */
@Slf4j
@ChannelHandler.Sharable
public class ListQueryRequestHandler extends SimpleChannelInboundHandler<ListQueryRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ListQueryRequestMessage msg) throws Exception {
        final ListQueryResponseMessage resMsg = new ListQueryResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final UserRelationService service = UserRelationServiceFactory.getService();
        final List<UserRelation> list = service.queryRelations(msg.getUserId(), msg.getIsFriend());

        resMsg.setResponse(true, list.size() + "条数据");
        final List<UserDto> users = UserServiceFactory.getService().getBatchUserInfo(
                Stream.concat(list.stream().map(item -> {
                    if (Objects.equals(item.getUserId(), msg.getUserId())) {
                        return item.getAnotherUserId();
                    } else return item.getUserId();
                }), Stream.of(msg.getUserId())).toList());
        // 添加状态
        users.forEach(item -> item.setLeave(SessionFactory.getSession().getChannel(item.getId()) == null));
        resMsg.setList(users);

        ctx.writeAndFlush(resMsg);


    }

}
